﻿@@master_page.html
<link href="css/page_interface_detail.css?v=1" rel="stylesheet" />
<div id="app">
    <div v-if="data">
        <h1>
            {{data.Name}} <button @click="changeTag" type="button" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Tooltip on bottom"><i class="mdi-toggle-switch mdi"></i>切换模式</button>
        </h1>
        <div class="url">
            {{ data.HttpMethod }}: {{data.Url}}
        </div>
        <div :class="{'hidden': !toggle}" >
            <div class="parameter" v-if="data.DataModel.DefaultParameters && data.DataModel.DefaultParameters.length > 0">
                <div class="form-group" v-for="param in data.DataModel.DefaultParameters" :key="param.Name">
                    <label class="control-label" :style="{ display: param.ValueIsReadOnly ? 'none' : 'block' }">{{param.Description}} [ {{ param.Name }} {{param.FieldOperatorString}}]:</label>

                    <div v-if="param.ValueType=='Byte[]'">
                        <input @change="handleFileChange($event, param)" class="form-control" type="file"   :placeholder="param.ValueType">
                    </div>
                    <div v-else-if="param.ValueIsReadOnly==false">
                        <input v-model="param.Value" type="text"   class="form-control" :placeholder="param.ValueType">
                    </div>
                    <div v-else-if="param.ValueIsReadOnly==true" :style="{ display: param.ValueIsReadOnly ? 'none' : 'block' }">
                        <input v-model="param.Value" type="text" class="readonly form-control" readonly="readonly"   placeholder="">
                    </div>
                </div>
            </div>
            <div class="parameter" v-if="data.DataModel.OrderDynamicParemters">
                <label>
                    排序:
                </label>
                <textarea id="txtOrderDynamicParemters" placeholder="格式：[{FieldName:FieldName,OrderByType:0}] ，其中： 0 升序, 1 倒序，FieldName是列表中的列">  </textarea>
            </div>
            <div class="parameter" v-if="!data.DataModel.OrderDynamicParemters">
                <input id="txtOrderDynamicParemters" type="hidden" />
            </div>
            <div class="form-group">
                <button class="btn   btn-primary m-r-10" v-on:click="submitRequest"><i class="mdi mdi-check-circle-outline"></i>提交</button>
                <button class="btn   btn-info m-r-10" v-on:click="saveParameters"><i class="mdi-content-save mdi"></i> 保存参数</button>
                <button class="btn   btn btn-pink m-r-10" v-on:click="loadParameters"><i class="mdi-autorenew mdi"></i>加载参数</button>
                <button class="btn   btn btn-secondary m-r-10" v-on:click="submitClose"><i class="mdi-close mdi"></i>关闭页面</button>
            </div>
            <div>
                <code>{{message}}</code>
            </div>
        </div>
        <div :class="{'hidden': toggle}">
            <div class="form-group">
                <label class="control-label">
                    Json参数:
                </label>
                <div id="editorJson" class="m-t-10" style="padding:10px;width: 100%; height: 300px;"></div>
            </div>
            <div class="form-group">
                <button class="btn   btn-primary m-r-10" v-on:click="submitRequestJson"><i class="mdi mdi-check-circle-outline"></i>提交</button>
                <button class="btn   btn-info m-r-10" v-on:click="saveParametersJson"><i class="mdi-content-save mdi"></i> 保存参数</button>
                <button class="btn   btn btn-pink m-r-10" v-on:click="loadParametersJson"><i class="mdi-autorenew mdi"></i>加载参数</button>
                <button class="btn   btn btn-secondary m-r-10" v-on:click="submitClose"><i class="mdi-close mdi"></i>关闭页面</button>
            </div>
            <div>
                <code>{{message}}</code>
            </div>
        </div>
    </div>
    <div v-else>
        <!-- 处理 data 为 null 的情况，可以显示加载中或错误信息 -->
        <p>Loading...</p>
    </div> 
    <div id="editor" class="m-t-10" style="padding:10px;width: 100%; height: 300px;"></div>

    <div v-if="responseUrl" class="alert alert-success m-t-10 m-b-10">
        <div class="m-b-10" v-if="data.HttpMethod=='Post'">Post同时支持Raw、表单和url参数</div>
        <div class="m-b-10" v-if="data.HttpMethod=='All'">Get Post 都支持,可以是Url参数、表单参数或者Raw</div>
        {{responseUrl}}
    </div>

</div> 
<script src="js/ace/src-min/ace.js"></script>
<script>
    var vueObj = new Vue({
        el: '#app',
        data: {
            data: null,
            error: null,
            response: "",
            responseUrl: null,
            toggle:true,
            message: "注意：如果找不到表需要到【菜单：实体表维护】点按钮【同步】建表"
        },
        mounted() {
            // 在组件加载时触发数据获取
            this.fetchData();
            var th = this;
            th.setEditorValue("{}");
            setTimeout(function () {
                var value = th.transformJsonArrayToObject(th.data.DataModel.DefaultParameters);
                th.setEditorJsonValue(JSON.stringify(value,null,4));
            },2000);
             
        },
        methods: {
            submitClose: function () {
                window.close();
            },
            submitRequestJson: function () {
                var vm = this;
                var json = vm.data; // Uncomment this line
                // 构造请求
                var fullUrl = json.Url;
                var json = ace.edit("editorJson").getValue(); 
                try {
                    json = JSON.parse(json);
                    if (Array.isArray(json))
                    {
                        json = { data: json };
                    }
                } catch (e) {
                    var editor = ace.edit("editor")
                    editor.setValue(JSON.stringify({ message: "json格式不标准" },null,4));
                    return;
                }
                var isUrlParameters = this.isUrlParameters(fullUrl);
                if (isUrlParameters)
                {
                    fullUrl = this.getUrlByUrlParameters(fullUrl);
                }
                // 发送 POST 请求
                axios.post(fullUrl, json , jwHeader)
                    .then(function (response) {
                        // 更新响应
                        vm.response = JSON.stringify(response.data, null, 4);
                        this.setEditorValue(vm.response);
                        this.setResponseUrl(fullUrl, json, isUrlParameters);
                     
                    }.bind(vm))
                    .catch(function (error) {
                        // 处理错误
                        vm.response = "网络错误";
                    }.bind(vm));
            },
            submitRequest: function () {

                var vm = this;
                var json = vm.data; // Uncomment this line
                // 构造请求
                var fullUrl = json.Url;
                var postData = {};
                if (json.DataModel.DefaultParameters) {
                    json.DataModel.DefaultParameters.forEach(function (param) {
                        postData[param.Name] = param.Value;
                    });
                }
                if (txtOrderDynamicParemters.value) {
                    postData["OrderDynamicParemters"] = txtOrderDynamicParemters.value;
                }
                var isUrlParameters = this.isUrlParameters(fullUrl);
                if (isUrlParameters) {
                    fullUrl = this.getUrlByUrlParameters(fullUrl);
                }
                // 发送 POST 请求
                axios.post(fullUrl, postData, jwHeader)
                    .then(function (response) {
                        // 更新响应
                        vm.response = JSON.stringify(response.data, null, 4);
                        this.setEditorValue(vm.response);
                        this.setResponseUrl(fullUrl, postData, isUrlParameters);

                    }.bind(vm))
                    .catch(function (error) {
                        // 处理错误
                        vm.response = "网络错误";
                    }.bind(vm));
            },
            fetchData: function () {
                var urlParams = new URLSearchParams(window.location.search);
                var idFromUrl = urlParams.get('id');
                // 发送 GET 请求
                axios.get('/PrivateReZeroRoute/100003/GetInternalDetail?id=' + idFromUrl, jwHeader)
                    .then(function (response) {
                        this.data = response.data;
                        this.error = null;
                        document.body.classList.add("lyear-layout-sidebar-close");
                    }.bind(this))
                    .catch(function (error) {
                        // 处理错误
                        this.error = error.message;
                        this.data = null;
                    }.bind(this));
            },
            handleFileChange: function (event, param) {
                // Handle the file change event
                var file = event.target.files[0];
                // Assuming you want to read the file as base64 for upload
                var reader = new FileReader();
                reader.onload = function () {
                    // Update the param value with the file content
                    param.Value = reader.result;
                };
                reader.readAsDataURL(file);
            },
            setEditorValue: function (formattedJson) {
                var editor = ace.edit("editor");
                editor.setTheme("ace/theme/twilight");
                editor.setOption("showPrintMargin", false);
                editor.session.setMode("ace/mode/json5");
                editor.setValue(formattedJson);
                editor.selection.clearSelection();
                editor.resize();

            },
            setEditorJsonValue: function (formattedJson) {
                var editor = ace.edit("editorJson");
                editor.setTheme("ace/theme/twilight");
                editor.setOption("showPrintMargin", false);
                editor.session.setMode("ace/mode/json5");
                editor.setValue(formattedJson);
                editor.selection.clearSelection();
                editor.resize();

            },
            saveParameters: function () {
                this.message = ("保存成功，点加载可以还原参数");
                localStorage.setItem("Parameters:" + this.data.Url, JSON.stringify(vueObj.$data.data.DataModel.DefaultParameters));
            },
            loadParameters: function () {
                this.message = ("加载成功，修改后可以保存");
                var key = "Parameters:" + this.data.Url;
                if (localStorage.getItem(key)) {
                    var items = JSON.parse(localStorage.getItem(key));
                    vueObj.data.DataModel.DefaultParameters = []; // 清空数组
                    items.forEach(function (item) {
                        vueObj.data.DataModel.DefaultParameters.push(item); // 向数组中添加元素
                    });
                }
                else {
                    this.message = ("浏览器没有找到保存，请先保存");
                }
            },
            saveParametersJson: function () {
                this.message = ("保存成功，点加载可以还原参数");
                var editor = ace.edit("editorJson");
                localStorage.setItem("ParametersJson:" + this.data.Url,  editor.getValue() );
            },
            loadParametersJson: function () {
                this.message = ("加载成功，修改后可以保存");
                var key = "ParametersJson:" + this.data.Url;
                if (localStorage.getItem(key)) { 
                    var editor = ace.edit("editorJson");
                    editor.setValue(localStorage.getItem(key));
                    editor.selection.clearSelection();
                }
                else {
                    this.message = ("浏览器没有找到保存，请先保存");
                }
            },
            changeTag: function ()
            {
                this.toggle = !this.toggle;
            },
            transformJsonArrayToObject: function (jsonArray) {
                let result = {};
                if (jsonArray) {
                    jsonArray.forEach(item => {
                        if ('Name' in item) {
                            result[item.Name] = null;
                        }
                    });
                }
                return result;   
            },
            setResponseUrl: function (fullUrl,json,isUrlParameters)
            {


                // 定义HTTP方法和原始URL  
                var httpMethod = this.data.HttpMethod;
                var baseUrl = window.location.origin + fullUrl;


                if (isUrlParameters)
                {
                    this.responseUrl = `${httpMethod} : ${baseUrl}`;
                    return;
                }

                // 将postData转换为URL参数  
                var queryParams = tools.jsonToUrl(json);
                if (queryParams)
                    queryParams = "?" + queryParams;
                // 使用模板字符串构建完整的响应URL  
                this.responseUrl = `${httpMethod} : ${baseUrl}${queryParams}`;
            },
            isUrlParameters: function (fullUrl)
            {
                var isUrlParameters = (fullUrl + "").indexOf("/{") > 0 && (fullUrl + "").indexOf("}") > 0;
                return isUrlParameters;
            },
            getUrlByUrlParameters: function (fullUrl) {
                var url = fullUrl;
                if (this.data.DataModel.DefaultParameters) {
                    this.data.DataModel.DefaultParameters.forEach(function (param) {
                        var regex = new RegExp("{" + param.Name + "}", "g");
                        url = url.replace(regex, param.Value);
                    });
                }
                return url;
            }
        }
    });
</script>
